import { Context } from "koa";
import { URLSearchParams } from "url";
import response from "../../utils/response"; // 统一返回接口
import UserService from "../service/UserService";
import paginate from "../../utils/paginate"

class UserController {
  async index(ctx: Context): Promise<any> {
    console.log('get请求用户页面---/user/');
    console.log(ctx.request.body);

    // 数据库连接测试 router(/user)-->controller-->service-->controller-->model
    const user = await UserService.getUserById(1);
    if (user) {
      response.success(ctx, user);
    } else {
      response.error(ctx,'账号不存在');
    }
  }

  /** 获取用户列表 */
  async getUserList(ctx : Context){
    // 解析路由参数http://localhost:9000/user/list?page=1&limit=5
    // 为URLSearchParams { 'page' => '1', 'limit' => '5' }
    const usp = new URLSearchParams(ctx.querystring);

    let page = 1, limit =5;
    let result = null;

    // 进行类型转换的时候要先判断能否转换为数字
    if (usp.get('page') && !isNaN(Number(usp.get('page')))){
      page = Number(usp.get('page'));
    }

    if (usp.get('limit') && !isNaN(Number(usp.get('limit')))) {
      limit = Number(usp.get('limit'));
    }

    const { rows, count } = await UserService.getUserListByPage(page, limit);
    result = paginate(rows, page, count, limit);
    response.success(ctx, result);
  }
}
export default new UserController